# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=openexr
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=3.3.3
pkgrel=2
pkgdesc='A high dynamic-range image file format library (mingw-w64)'
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://www.openexr.com/"
msys2_repository_url='https://github.com/AcademySoftwareFoundation/openexr'
msys2_references=(
  "purl: pkg:pypi/openexr"
  "cpe: cpe:/a:ilm:openexr"
  "cpe: cpe:/a:openexr:openexr"
)
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-imath"
         "${MINGW_PACKAGE_PREFIX}-libdeflate"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread-git")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
conflicts=(
  "${MINGW_PACKAGE_PREFIX}-ilmbase"
  "${MINGW_PACKAGE_PREFIX}-pyilmbase"
)
replaces=(
  "${MINGW_PACKAGE_PREFIX}-ilmbase"
  "${MINGW_PACKAGE_PREFIX}-pyilmbase"
)
source=("https://github.com/openexr/openexr/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        0006-cmake-soversion.patch
        0007-export-TypedAttribute-value.patch
        "https://github.com/AcademySoftwareFoundation/openexr/pull/2011.patch")
sha256sums=('0ffbd842a7ee2128d44affdea30f42294b4061293cde3aa75b61a53573413d1e'
            '5653da878ebbf5f3087bb529213931b48e151aef082b34e19d189e22be0411e7'
            '204777b48cde1c4d390789f10c5e429d5295be701f68a7937a90d0ecf271c048'
            'e88b851dafb7ecb34b8dce94b8f935cab6b3e1821a56289f6ea1ae0650361bdd')

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying $_patch"
    patch -Np1 -i "${srcdir}/$_patch"
  done
}

prepare(){
  cd "${srcdir}/${_realname}-${pkgver}"

  # https://github.com/AcademySoftwareFoundation/openexr/pull/2011
  apply_patch_with_msg \
    0006-cmake-soversion.patch \
    0007-export-TypedAttribute-value.patch \
    2011.patch
}

build() {
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  CXXFLAGS+=" -Wno-ignored-attributes"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      ${extra_config[@]} \
      -DBUILD_SHARED_LIBS=ON \
      -DBUILD_TESTING=OFF \
      -DOPENEXR_BUILD_EXAMPLES=OFF \
      -S "${_realname}-${pkgver}" \
      -B "build-${MSYSTEM}"

  cmake --build "build-${MSYSTEM}"
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/cmake -DBUILD_TESTING=ON ../${_realname}-${pkgver}
  ${MINGW_PREFIX}/bin/cmake --build .
  ${MINGW_PREFIX}/bin/ctest.exe ./ || true
}

package() {
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE.md" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE.md"
}
